package pl.task;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;

public class TaskService extends IntentService
{
    private final Handler handler = new Handler();

    public TaskService()
    {
        super("TaskService");
    }

    @Override
    protected void onHandleIntent(Intent intent)
    {
        handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    Toast.makeText(TaskService.this, "Service Started", Toast.LENGTH_SHORT).show();
                }
            });
        final long endTime = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < endTime)
        {
            synchronized (this)
            {
                try
                {
                    wait(endTime - System.currentTimeMillis());
                }
                catch (Exception e)
                {
                }
            }
        }
        handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    Toast.makeText(TaskService.this, "Service Finished", Toast.LENGTH_SHORT).show();

                    final Intent mainIntent = new Intent(Intent.ACTION_MAIN);
                    mainIntent.addCategory("pl.task.HOME");
                    mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(mainIntent);
                }
            });
    }
}
